# code:utf8
import json
from datetime import datetime
import math

from zc_core.pipelines.helper.catalog_helper import CatalogHelper
from zc_core.pipelines.helper.gov_cat_helper import GovCatHelper
from zc_core.util.batch_gen import time_to_batch_no
from zc_core.model.items import Catalog, Brand, Supplier, ItemData, ItemPoolData, Spu, Sku, Order
from zc_core.util.common import parse_number, parse_time
from pyquery import PyQuery

from zc_core.util.encrypt_util import md5
from huiemall.matcher import *


# 解析catalog列表
from zc_core.util.sku_id_parser import convert_id2code


def parse_index_catalog(response):
    jpy = PyQuery(response.text)
    root_list = jpy('ul.cate-list a')
    sub_list = jpy('div.son-cate-wrap div.son-cate')

    cats = list()
    for idx, nav1_link in enumerate(root_list.items()):
        cat1_id = ''
        son_cate = sub_list.eq(idx)
        cat2_links = son_cate('div.cate-line ul.cate-line-list a')
        if cat2_links:
            if cat2_links:
                for cat2_link in cat2_links('a').items():
                    cat2_id = match_cat_id(cat2_link.attr('href')).strip()
                    cat2_name = cat2_link.text().strip()
                    if cat2_id and not cat1_id:
                        cat1_id = cat2_id[:-4]
                    cat2 = _build_catalog(cat2_id, cat2_name, cat1_id, 2)
                    cats.append(cat2)

        cat1_name = nav1_link.text().strip()
        cat1 = _build_catalog(cat1_id, cat1_name, '', 1)
        cats.append(cat1)

    return cats


# 解析catalog列表
def add_fixed_catalog(cats):
    fixed_root_cats = {
        'A01': '土地、建筑物及构筑物',
        'A02': '通用设备',
        'A03': '专用设备',
        'A04': '文物和陈列品',
        'A05': '图书和档案',
        'A06': '家具用具',
        'A07': '纺织原料、毛皮、被服装具',
        'A08': '纸、纸制品及印刷品',
        'A09': '办公消耗用品及类似物品',
        'A10': '建筑建材',
        'A11': '医药品',
        'A12': '农林牧渔业产品',
        'A13': '矿与矿物',
        'A14': '电力、城市燃气、蒸汽和热水、水',
        'A15': '食品、饮料和烟草原料',
        'A16': '炼焦产品、炼油产品',
        'A17': '基础化学品及相关产品',
        'A18': '橡胶、塑料、玻璃和陶瓷制品',
        'A19': '无形资产',
        'A99': '其他货物',
    }

    for key in fixed_root_cats.keys():
        cat = _build_catalog(key, fixed_root_cats.get(key), '', 1)
        cats.append(cat)

    return cats


# 解析catalog列表
def parse_search_catalog(response):
    meta = response.meta
    all_cats = meta.get('cats')
    search_cat_list = json.loads(response.text).get('userarea', {}).get('cidlist', [])

    full_id_list = list()
    cat1_id_list = list()
    for cat in all_cats:
        full_id_list.append(cat.get('catalogId'))
        if cat.get('level') == 1:
            cat1_id_list.append(cat.get('catalogId'))
    for row in search_cat_list:
        scat_id = row.get('Name')
        scat_name = row.get('cname')
        if scat_id in full_id_list:
            continue
        pid = 'P'
        for nav_cat1_id in cat1_id_list:
            if scat_id.startswith(nav_cat1_id) and len(nav_cat1_id) > len(pid):
                pid = nav_cat1_id
        cat3 = _build_catalog(scat_id, scat_name, pid, 2)
        all_cats.append(cat3)

    return all_cats


def _build_catalog(cat_id, cat_name, parent_id, level):
    cat = Catalog()
    cat['catalogId'] = cat_id
    cat['catalogName'] = cat_name
    cat['parentId'] = parent_id
    cat['level'] = level
    if level == 2:
        cat['leafFlag'] = 1
    else:
        cat['leafFlag'] = 0
    cat['linkable'] = 1

    return cat


# 解析total_supplier
def parse_total_supplier(response):
    return int(json.loads(response.text).get('userarea', {}).get('page', '0'))


# 解析supplier列表
def parse_supplier(response):
    meta = response.meta
    js = json.loads(response.text)
    sp_list = js.get('userarea', {}).get('gyslist', [])
    suppliers = list()
    for sp in sp_list:
        supplier = Supplier()
        supplier['id'] = sp.get('gysguid')
        supplier['name'] = sp.get('danweiname')
        supplier['score'] = sp.get('creditpoint')
        supplier['sales'] = sp.get('sales')
        supplier['area'] = sp.get('areaname')
        supplier['batchNo'] = meta.get('batchNo')
        suppliers.append(supplier)

    return suppliers


# pool：查询总页数
def parse_search_total_page(response):
    data = json.loads(response.text).get('userarea', {}).get('goodsinfo', {})
    total = data.get('AllCountNum', 0)
    size = data.get('ReturnNum', 12)
    if size and total:
        return math.ceil(total / size)

    return 0


# 解析total_sku_page
def parse_total_sku_page(response):
    data = json.loads(response.text).get('userarea', {}).get('productslist', {})
    total = data.get('AllCountNum', 0)
    size = data.get('ReturnNum', 8)
    if size and total:
        return math.ceil(total / size)

    return 0


# 解析total_sku
def parse_total_sku(response):
    data = json.loads(response.text).get('userarea', {}).get('productslist', {})
    total = data.get('AllCountNum', 0)
    if total:
        return total

    return 0


# 统一构建商品编号方法
def build_sku_id(spu_id, supplier_id):
    return md5('%s_%s' % (spu_id, supplier_id))


# 解析sku列表
def parse_item_data(response):
    cat_helper = CatalogHelper()
    gov_cat_helper = GovCatHelper()
    meta = response.meta
    js = json.loads(response.text)
    items = list()
    if 'userarea' in js:
        data_list = js.get('userarea', {}).get('productslist', {}).get('Goods', [])
        for data in data_list:
            item = ItemData()
            batch_no = meta.get('batchNo')
            sp_id = meta.get('spId')
            spu_id = data.get('productid')
            sku_id = build_sku_id(spu_id, sp_id)
            imgs = data.get('pic')
            cat_id = data.get('cid')

            # -------------------------------------------------
            item['batchNo'] = batch_no
            item['skuId'] = sku_id
            item['spuId'] = spu_id
            item['skuName'] = data.get('productname').strip()
            sp_sku_id = ''
            if imgs:
                sku_img = imgs[0].get('imgsrc')
                if sku_img:
                    item['skuImg'] = sku_img
                    sp_sku_id = match_sp_sku_id_from_img(sku_img)

            item['catalog2Id'] = data.get('cid')
            cat_helper.fill(item)
            gov_cat_name = gov_cat_helper.get_by_id(cat_id)
            if gov_cat_name:
                item['govCatId'] = cat_id
                item['govCatName'] = gov_cat_name
            price = parse_number(data.get('price', '0'))
            item['salePrice'] = price
            item['originPrice'] = price
            brand = data.get('brandname')
            if brand:
                item['brandId'] = md5(brand)
                item['brandName'] = brand
            item['supplierId'] = data.get('sid')
            if 'sname' in data and data.get('sname'):
                sp_name = data.get('sname')
            else:
                sp_name = js.get('userarea', {}).get('gysinfo', {}).get('danweiname', '')
            item['supplierName'] = sp_name
            # 供应商商品编号
            if sp_sku_id:
                sp_sku_code = sp_sku_id
                if sp_name and '得力' in sp_name:
                    sp_sku_code = convert_id2code('deli', sp_sku_id)
                item['supplierSkuCode'] = sp_sku_code
                item['supplierSkuId'] = sp_sku_id
            item['onSaleTime'] = parse_time(data.get('adddate'), '%Y%m%d%H%M%S')
            item['genTime'] = datetime.utcnow()
            items.append(item)
            # -------------------------------------------------

    return items


# 解析PoolData
def parse_spu(response):
    cat_helper = CatalogHelper()
    gov_cat_helper = GovCatHelper()
    meta = response.meta
    js = json.loads(response.text)
    items = list()
    if 'userarea' in js:
        data_list = js.get('userarea', {}).get('goodsinfo', {}).get('Goods', [])
        for data in data_list:
            spu = Spu()
            cat_id = data.get('cid')
            # 实际销售价格
            price = parse_number(data.get('price', None))
            if price <= 0:
                continue
            # -------------------------------------------------
            spu['batchNo'] = meta.get('batchNo')
            spu['spuId'] = data.get('productid')
            spu['skuName'] = data.get('productname').strip()
            spu['salePrice'] = price
            spu['originPrice'] = price
            spu['soldCount'] = int(parse_number(data.get('salesvolume')))
            sku_img = data.get('pic')
            if sku_img:
                spu['skuImg'] = sku_img
            spu['catalog2Id'] = cat_id
            cat_helper.fill(spu)
            gov_cat_name = gov_cat_helper.get_by_id(cat_id)
            if gov_cat_name:
                spu['govCatId'] = cat_id
                spu['govCatName'] = gov_cat_name
            brand = data.get('brandname')
            if brand:
                spu['brandId'] = md5(brand)
                spu['brandName'] = brand
            spu['onSaleTime'] = parse_time(data.get('adddate'), '%Y%m%d%H%M%S')
            spu['genTime'] = datetime.utcnow()

            items.append(spu)
            # -------------------------------------------------

    return items


# 解析由订单发起商品补充
def parse_search_spu(response):
    cat_helper = CatalogHelper()
    gov_cat_helper = GovCatHelper()
    meta = response.meta
    spus = list()
    js = json.loads(response.text)
    if 'userarea' in js:
        data_list = js.get('userarea', {}).get('goodsinfo', {}).get('Goods', [])

        for data in data_list:
            spu = Spu()
            cat_id = data.get('cid')
            # 实际销售价格
            price = parse_number(data.get('price', None))
            if price <= 0:
                continue
            spu_id = data.get('productid', None)
            if not spu_id:
                continue
            # -------------------------------------------------
            spu['batchNo'] = meta.get('batchNo')
            spu['spuId'] = spu_id
            spu['skuName'] = data.get('productname').strip()
            spu['salePrice'] = price
            spu['originPrice'] = price
            spu['soldCount'] = int(parse_number(data.get('salesvolume')))
            sku_img = data.get('pic')
            if sku_img:
                spu['skuImg'] = sku_img
            spu['catalog2Id'] = cat_id
            cat_helper.fill(spu)
            gov_cat_name = gov_cat_helper.get_by_id(cat_id)
            if gov_cat_name:
                spu['govCatId'] = cat_id
                spu['govCatName'] = gov_cat_name
            brand = data.get('brandname')
            if brand:
                spu['brandId'] = md5(brand)
                spu['brandName'] = brand
            spu['onSaleTime'] = parse_time(data.get('adddate'), '%Y%m%d%H%M%S')
            spu['genTime'] = datetime.utcnow()
            spus.append(spu)
            # -------------------------------------------------

    return spus


# =============================================
# 解析order列表页数
def parse_total_page(response):
    jpy = PyQuery(response.text)

    return int(jpy('div.page_wrap a.nextPag').prev().text().strip())


# 解析order列表
def parse_order(response):
    js = json.loads(response.text)

    orders = list()
    if 'userarea' in js:
        order_list = js.get('userarea', {}).get('gonggaolist', [])
        if order_list:
            for row in order_list:
                # 订单主数据
                order = _build_order(row)
                orders.append(order)

    return orders


def _build_order(row):
    order_detail_url = 'http://www.huiemall.com/HeFei/noticedetail.html?type=cj&gonggaoguid={}&gonggaotype=undefined'

    order = Order()
    id = row.get('gonggaoguid')
    title = row.get('gonggaotitle')
    jpy = PyQuery(title)

    order['id'] = id
    order['url'] = order_detail_url.format(id)
    order_time = parse_time(row.get('gonggaopubdate'))
    order['orderTime'] = order_time
    order['batchNo'] = time_to_batch_no(order_time)
    order['title'] = jpy.text().replace('\n', '').strip()
    order['genTime'] = datetime.utcnow()

    return order


# 解析order详情
def parse_order_item(response):
    meta = response.meta
    order_id = meta.get('orderId')
    order_time = meta.get('orderTime')
    js = json.loads(response.text)

    orders = list()
    if 'userarea' in js:
        detail = js.get('userarea', {}).get('detail', [])
        if detail:
            orders = _build_order_item(detail, order_id, order_time)

    return orders


def _build_order_item(detail, order_id, order_time):
    jpy = PyQuery(detail.get('gonggaocontent'))

    info = jpy('h2.table-item-title:contains("项目信息") + table.table-information')
    if order_id and info:
        order_dept_td = jpy('td.tab-right:contains("采购人名称") + td.pl17')
        user_id_td = jpy('td.tab-right:contains("采购人联系方式") + td.pl17')
        supplier_name_td = jpy('td.tab-right:contains("中标供应商") + td.pl17')
        order_time_td = jpy('td.tab-right:contains("公告日期") + td.pl17')
        if not order_dept_td:
            return list()
        order_dept = order_dept_td.text().strip()
        if not supplier_name_td:
            return list()
        supplier_name = supplier_name_td.text().strip()
        user_id = ''
        if user_id_td:
            user_id = user_id_td.text().strip()
        if not order_time:
            order_time = parse_time(order_time_td.text().strip(), fmt='%Y/%m/%d %H:%M:%S')
        item_list = list()
        tr_list = jpy('h2.table-item-title:contains("商品信息") + table.table-information tr')
        if len(tr_list):
            for idx, tr in enumerate(tr_list.items()):
                tds = tr('td')
                if idx > 0 and len(tds) != 3 and len(tds) != 1:
                    order_item = dict()
                    order_item['id'] = order_id + '_' + str(idx)
                    order_item['orderId'] = order_id
                    order_item['orderUser'] = user_id
                    order_item['orderDept'] = order_dept
                    order_item['supplierName'] = supplier_name
                    order_item['orderTime'] = order_time
                    order_item['batchNo'] = time_to_batch_no(order_time)
                    order_item['genTime'] = datetime.utcnow()
                    if idx > 0 and len(tds) == 4:
                        order_item['skuName'] = tds.eq(0).text().strip()
                        order_item['count'] = round(parse_number(tds.eq(1).text().strip()))
                        order_item['amount'] = parse_number(tds.eq(3).text().strip())
                    elif idx > 0 and len(tds) == 7:
                        order_item['spuId'] = match_spu_id(tds.eq(0)('a').attr('href'))
                        order_item['count'] = round(parse_number(tds.eq(2).text().strip()))
                        order_item['amount'] = parse_number(tds.eq(6).text().strip())
                    item_list.append(order_item)

        return item_list
